package spring.cloud.tasks.executor.listener.task_execute;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import spring.cloud.tasks.executor.listener.TreeCacheListener;
import spring.cloud.tasks.executor.utils.log.LogUtils;

/**
 * 作业立刻终止
 */
@Slf4j
@Setter
@Getter
class TriggerTaskStopAtOnceListener extends TreeCacheListener {

    private final TaskExecuteListenerHolder taskExecuteListener;

    public TriggerTaskStopAtOnceListener(TaskExecuteListenerHolder taskExecuteListener) {
        this.taskExecuteListener = taskExecuteListener;
    }

    @Override
    protected void dataChanged(CuratorFramework curatorFramework, String path, TreeCacheEvent treeCacheEvent) {
        if (taskExecuteListener.isShutdown) {
            return;
        }
        if (TreeCacheEvent.Type.NODE_ADDED == treeCacheEvent.getType() || TreeCacheEvent.Type.NODE_UPDATED == treeCacheEvent.getType()) {
            try {
                LogUtils.info(log, taskExecuteListener.taskId, "job is going to be stopped at once.");
                taskExecuteListener.taskExecutor.getTaskExecuteEngine().forceStop();
            } finally {
                taskExecuteListener.zookeeper.delete(path);
            }
        }
    }
}
